package com.self.study.subjectsstudy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.self.study.subjectsstudy.common.ResultInfo;
import com.self.study.subjectsstudy.config.VxConfig;
import com.self.study.subjectsstudy.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;

/**
 * @author lidd
 * @time 2021/3/8 11:12
 */
@Slf4j
@RestController
@RequestMapping("/study")
public class LoginController {

    @Autowired
    private VxConfig vxConfig;


    @RequestMapping("login")
    public ResultInfo login(@RequestParam("code") String code) {
        String site = "https://api.weixin.qq.com/sns/jscode2session";
        String urlParm = site + MessageFormat.format("?appid={0}&secret={1}&js_code={2}&grant_type={3}",
                vxConfig.getAppid(),
                vxConfig.getAppsecret(),
                code,
                vxConfig.getGrantType()
        );
        String content = HttpUtil.sendGet(urlParm);
        log.info("微信code登录返回内容：" + content);
        JSONObject jsonObject = JSON.parseObject(content);
        String openId = jsonObject.getString("openid");
        String errmsg = jsonObject.getString("errmsg");
        return new ResultInfo(ResultInfo.Status.SUCCESS).result(StringUtils.isEmpty(openId) ? errmsg : openId);

    }
}
